#!/bin/sh /etc/rc.common

START=99

IPSEC_SECRETS_FILE=/etc/ipsec.secrets
IPSEC_CONN_FILE=/etc/ipsec.conf

setup_login() {
	config_get enabled $1 enabled
	[ "$enabled" -eq 0 ] && return 0
	config_get username $1 username
	config_get password $1 password
	[ -n "$username" ] || return 0
	[ -n "$password" ] || return 0
	echo "$username : XAUTH '$password'" >> $IPSEC_SECRETS_FILE
}

start() {
	local vt_enabled=$(uci -q get ipsec.@service[0].enabled)
	[ "$vt_enabled" = 0 ] && return 1
	
	local vt_clientip=$(uci -q get ipsec.@service[0].clientip)
	local vt_clientdns=$(uci -q get ipsec.@service[0].clientdns)
	[ -z "$vt_clientdns" ] && local vt_clientdns="8.8.4.4"
	local vt_secret=$(uci -q get ipsec.@service[0].secret)
	
	cat > $IPSEC_CONN_FILE <<EOF
# ipsec.conf - strongSwan IPsec configuration file

# basic configuration

config setup
    # strictcrlpolicy=yes
    uniqueids=never

# Add connections here.

conn xauth_psk
	keyexchange=ikev1
	ike=aes128-sha1-modp2048,aes128-sha1-modp1024,3des-sha1-modp1024,3des-sha1-modp1536
  esp=aes128-sha1,3des-sha1
	left=%defaultroute
	leftauth=psk
	leftsubnet=0.0.0.0/0
	right=%any
	rightauth=psk
	rightauth2=xauth
	rightsourceip=$vt_clientip
	rightdns=$vt_clientdns
	auto=add
EOF

	cat > /etc/ipsec.secrets <<EOF
# /etc/ipsec.secrets - strongSwan IPsec secrets file
: PSK "$vt_secret"
EOF

	config_load ipsec
	config_foreach setup_login users
	
	/usr/lib/ipsec/starter --daemon charon --nofork > /dev/null 2>&1 &
	fw3 -q reload 2>&1 &
}

stop() {
	ps -w | grep "/usr/lib/ipsec" | grep -v "grep" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1
	fw3 -q reload 2>&1
}